package com.gitee.ixtf.vertx.internal.converter

import com.gitee.ixtf.vertx.ParameterConverter
import io.vertx.core.eventbus.Message
import io.vertx.ext.web.FileUpload
import io.vertx.ext.web.RoutingContext
import jakarta.ws.rs.DefaultValue
import jakarta.ws.rs.FormParam
import java.lang.reflect.Parameter

class FormParamParameterConverter(
    private val parameter: Parameter,
) : ParameterConverter<Any?> {
  private val key by lazy { parameter.getAnnotation(FormParam::class.java).value }
  private val fileUploadElement by lazy { FileUpload::class.java.isAssignableFrom(parameter.type) }
  private val defaultValue by lazy { parameter.getAnnotation(DefaultValue::class.java)?.value }
  private val converter by lazy { implicitConverter(parameter) }
  private val convert by lazy { defaultValue?.let { converter.convert(it) } }

  override suspend fun convert(rc: RoutingContext) =
      if (fileUploadElement) rc.fileUploads().firstOrNull { key == it.name() }
      else rc.request().getFormAttribute(key)?.let { converter.convert(it) } ?: convert

  override suspend fun convert(message: Message<*>) =
      message.headers().get(key)?.let { converter.convert(it) } ?: convert
}
